package com.liyy.platform.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

@Service
public class ContractProxySupplyService {

    private final Logger logger=Logger.getLogger(String.valueOf(getClass()));
    @Autowired
    private DiscoveryClient discoveryClient;//用来从服务注册中心获取服务的相关信息
    @Autowired
    private RestTemplate restTemplate;

    /*添加、更新方法
    使用@CacheRemove开启更新方法时清空缓存功能，用commandKey属性指定清理请求缓存的请求命令位置*/
    @CacheRemove(commandKey = "getContractProxySupplyList")
    public void saveContractProxySupply(){
        restTemplate.getForObject("http://os-search/search/contractProxySupply/saveContractProxySupply",String.class);
    }

//    @CacheResult //@CacheResult为此方法开启请求缓存功能,@CacheKey根据goodsName作为key来进行请求缓存； 请求缓存不可用（待完善）
    @HystrixCommand( fallbackMethod = "error")//添加HystrixCommand断路器机制
    public List getContractProxySupplyList(String goodsName, String goodsBrand, String goodsAttr,
                                           @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "10") int pageSize ){
        ServiceInstance instance = discoveryClient.getLocalServiceInstance();
        logger.info("本次服务的 Host:"+instance.getHost()+","+"Port:"+instance.getPort()+","+"ServiceId:"+instance.getServiceId());
        return restTemplate.getForObject("http://os-search/search/contractProxySupply/getContractProxySupplyList",List.class);
    }

    //容错机制触发后的处理方法
    public List error(String goodsName, String goodsBrand, String goodsAttr,
                      @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "10") int pageSize){
        List errorlist=new ArrayList();
        Map params=new HashMap();
        params.put("state","请求失败");
        params.put("message","请您过一段时间继续尝试");
        errorlist.add(params);
        return errorlist;
    }

}
